﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Brjnk.Maps.Downloader
{
    public class DownloadScheduler
    {
        PriorityQueue<DownloadTaskWithUpdater> queue;

        IOverloadProtection overloadProtection;

        public DownloadScheduler(IOverloadProtection overloadProtection)
        {
            this.overloadProtection = overloadProtection;
            queue = new PriorityQueue<DownloadTaskWithUpdater>(new DownloadTaskPriorities());
        }

        public void Add(DownloadTaskWithUpdater task)
        {
            queue.Add(task);
        }

        public DownloadTaskWithUpdater GetNextTask(DownloadThread thread)
        {
            var wait = overloadProtection.GetRemainingTime(thread);
            if (wait.Ticks > 0)
                System.Threading.Thread.Sleep(wait);
            while (true)
            {
                bool success = false;
                var item = queue.Dequeue(out success);
                if (!success) return null;
                if (item.Task.CancelRequested)
                {
                    item.Updater.updateState(DownloadTaskState.Cancelled);
                    item.Updater.raiseCompleted();
                    continue;
                }
                return item;
            }
        }

        public void IncrementOverloadProtection(DownloadThread thread, ulong size)
        {
            overloadProtection.Increment(thread, size);
        }

    }
}
